'use strict';

const Controller = require('egg').Controller;

/**
 * 请求入口
 */
class SpiderController extends Controller {
  async index() {

    var target = this.ctx.query.target;
    console.log('spider controller', this.ctx.queries);

    if (!target) {
      this.ctx.body = {
        code: -100,
        msg: 'target参数不能为空！'
      }
    } else {
      const result = await this.service.spider.index(target);
      this.ctx.body = {
        code: 0,
        msg: '爬虫执行成功' + result ? '成功' : '失败'
      }
    }
  }

  async publish() {
    const result = await this.service.spider.publish();
    // console.log(result);
    this.ctx.body = {
      code: 0,
      msg: '修改成功！'
    }
  }

  async batchIgnore() {
    const result = await this.service.spider.changeStatus(this.ctx.request.body.oids, 'IGNORE');
    this.ctx.body = {
      code: 0,
      msg: '忽略成功！'
    }
  }

  async save() {
    // console.log('save',this.ctx.request.body)
    const result = await this.service.spider.save(this.ctx.request.body.params);
    this.ctx.body = {
      code: 0,
      msg: '确认成功！'
    }
  }

  async star(){
    // console.log('star',this.ctx.request.body)
    const result = await this.service.spider.star(this.ctx.request.body);
    this.ctx.body = {
      code: 0,
      msg: '确认成功！'
    }
  }


  async batchConfirm() {
    const result = await this.service.spider.changeStatus(this.ctx.request.body.oids, 'CONFIRM');
    this.ctx.body = {
      code: 0,
      msg: '确认成功！'
    }
  }

  async showJobByOid() {
    var oid = this.ctx.query.oid;
    if (!oid) {
      this.ctx.body = {
        code: -100,
        msg: 'oid参数不能为空！'
      }
    } else {
      const result = await this.service.spider.showJobByOid(oid);
      this.ctx.body = {
        code: 0,
        data: result
      }
    }
  }


  async getLocalPage(){
    this.service.spider.huntLocalPage();
    this.ctx.body = {
      code: 0,
      data: 'getLocalPage'
    }
  }


  async screenShot(){
    let result = await this.service.spider.screenShot();
    this.ctx.body = {
      code: 0,
      data: result
    }
  }

  async create() {
    // console.log('create come in', this.ctx.request.body)
    let createPromise = await this.service.spider.createJob(this.ctx.request.body).catch( err => {
      console.error(err);
      this.ctx.body = {
        code: 101,
        data: null,
        msg: err
      }
    });

    this.ctx.body = {
      code: 0,
      data: null,
      msg: '创建成功'
    };
    
    return createPromise;
  }
}

module.exports = SpiderController;